
<template>
  <div class="app-container">
    <div v-show="false" id="report" class="print">
      <div v-for="item in printArr" :key="item.lotNo" style="width: 60mm; height: 40mm; page-break-after: always">
        <p style="text-align: center">K.L样品针车标签</p>
        <div class="List">
          <div class="left">
            <p style="margin: 0">{{ item.date }}</p>
            <!-- <canvas id="canvas"></canvas> -->
            <img :src="item.img" alt="" style="width: 80px; height: 80px" />
            <p>荣信研发</p>
          </div>
          <div class="right">
            <p>{{ item.orderId }}</p>
            <p>姓名: {{ item.name }}</p>
            <p>号码: {{ item.number }}</p>
            <p>数量: {{ item.count }}</p>
          </div>
        </div>
      </div>
    </div>

    <Find @clickNumber1="clickNumber"  @Launchform="Launchform3"  :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <Find  @Launchform="Launchform1"  :OriginalFilter="{ static: true }" :formList="formList2" :searchImg="false" @findClicked="findClicked2" />
    <div class="mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '10px 10px 0' }" class="mt10">
        <div slot="header" class="f16">
          <span style="font-weight: 600" class="mr55">扫描下单条码</span>
        </div>
        <div class="flex mt10" style="align-items: center">
          <div class="f14 mr55">PS:扫描指令单标签时，请确认光标置于此栏位</div>
          <div class="f14 mr55">
            <span class="mr10">扫描条码</span>
            <el-input @keydown="(event:any) => handleKeyDown(event)" v-model="scanCode" style="width: 414px; height: 25px; font-size: 20px" />
          </div>
          <div>
            <el-radio-group v-model="radio" class="ml-4" style="margin-left: 20px;margin-left: 20px;">
              <el-radio label="正单" size="large">正单</el-radio>
              <el-radio label="补单" size="large">补单</el-radio>
            </el-radio-group>
          </div>
          <div class="flex AIC" style="margin-left: 15px;">
            <span class="mr10">扫描信息</span>
            <div :class="flagBC === '0' ? '' : flagBC === '1' ? 'susses' : 'error'" style="width: 250px; height: 25px; border: 1px solid black">
              {{ scanMessage }}
            </div>
          </div>
        </div>
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <h1 class="f16">针车派工扫描记录</h1>
        <Table
          :isLoading="isLoading"
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :outTableHeight="160"
          @currentRow="currentRow3"
          summary
          @selectList="selectTable4List"
          @inputChange="inputChange"
        />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '0px 5px 5px' }">
        <PageModule :PageData="{ total: total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
export default defineComponent({
  // 定义组件的名称
  name: 'TheNeedleCartSentMen'
})

</script>
<script lang="ts" setup>
import { defineComponent, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
import { AcquisitionModel, selectList } from '@/plugins/mixin'
import LoginWork from '@/utils/LoginWork'
import type { formListType } from '@/components/Find/index.vue'
import JMessage from '@/utils/JMessage'
import {getList,deleteList, getStaffList } from '@/api/exploitation/BoardBuildingCompleted'
import qrcode from 'qrcode'
// 修改
const inputChange = async(row:any) => {
  const result = await service.post<any,any>(`/mes/pc/order/prodStatus/updateProdStatusById`,row)
    if(result.code === 200){
    getTableList()
    ElMessage.success(result.msg)
  }else{
    getTableList()
    ElMessage.error(result.msg)
  }
}

const clickNumber = (row:any) => {
  if(row === '1'){
    getListParms.value.prodStep = '正单'
  }
  if(row === '0'){
    getListParms.value.prodStep = ''
  }
  if(row === '2'){
    getListParms.value.prodStep = '补单'
  }
}

const printArr = ref([]) as any
const selectTableLists = ref([])
const selectTable4List = (selectedList: any) => {
  selectTableLists.value = selectedList
  printArr.value = selectTableLists.value.map((item: any) => {
    let qrCodeData = item.stitchBarcode
    qrcode.toDataURL(qrCodeData, (err: any, url: any) => {
      if (err) {
        JMessage.error(err)
      } else {
        qrCodeData = url
      }
    })
    return {
      img: qrCodeData,
      date: item.prodDate,
      orderId: item.orderId,
      name: item.workerName,
      number: item.sizeNo,
      count: item.prodQty
    }
  })
}



const findClicked2 = (content: string) => {
  if (content === '打印派工标签') {
    if (selectTableLists.value.length === 0) {
      JMessage.warning('请打勾数据')
      return
    }
    const printHTML = (document.querySelector('#report') as any).innerHTML
    window.document.body.innerHTML = printHTML
    window.print() // 调用浏览器的打印功能打印指定区域
    window.location.reload() // 打印完成后重新加载页面
  }
  
}

const formList2 = ref([
  {
    type: 'select',
    selectP: '厂商',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入补单原因',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入补单数量',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '打印派工标签'
  },
  {
    type: 'button',
    checkboxLabel: '导出补单明细表'
  }
]) as any

const deleteListParms = ref()

const currentRow3 = (row:any) => {
  deleteListParms.value = row
}
const handleDeleteList = async () => {
  const result = await deleteList(deleteListParms.value)
  if(result.code === 200){
    ElMessage.success(result.msg)
    getTableList()
  }else{
    ElMessage.error(result.msg)
  }
}

// 查询
const getListParms = ref({
  brand: "",
  choose: "9",
  completeEndTime: "",
  completeStartTime: "",
  dataScope: "",
  deliveryEndTime: "",
  deliveryStartTime: "",
  isAsc: "",
  orderByColumn: "",
  orderId: "",
  pageNum: 0,
  pageSize: 0,
  prodStep: "",
  prodUserName: "",
  reasonable: true,
  style: "",
  workerUser: ""
})

const Launchform3 = (row:any) => {
  getListParms.value.orderId = row[0].inputValue
  getListParms.value.brand = row[1].selectValue
  getListParms.value.style = row[2].inputValue
  getListParms.value.deliveryEndTime = row[3].dateValue[1]
  getListParms.value.deliveryStartTime = row[3].dateValue[0]
  getListParms.value.prodUserName = row[4].selectValue
  getListParms.value.completeStartTime = row[5].dateValue[0]
  getListParms.value.completeEndTime = row[5].dateValue[1]
}

const getTableList = async () => {
  isLoading.value = true
  const result = await getList(getListParms.value) 
  if(result.rows.length === 0){
    tableData.value = []
  }else{

  
    tableData.value = result.rows.map((item:any) => {
    item.change = true
    item.disableConfirm = true
    return item
  })
  tableData.value = result.rows.map((item:any) => { 
        item.photoPath = Object.values(result.files).find((item1:any) => {  
          return item1.fileId === item.photoId; // 查找合匹配的 photoId  
        });  
        

        return item
      })
  imgList.value = result.rows.map((item:any) => {
          const {buckName,fileName} = item.photoPath
          return {buckName,fileName}
      })
  await Promise.all(
    tableData.value.map(async (item:any) => {
        const result = await service.get<any, any>(`/file/oss/view/${item.photoPath.buckName}/${item.photoPath.fileName}`);
        item.photoPath = 'data:image/png;base64,'+result.data
        return 'data:image/png;base64,'+result.data
      })
    );
    imgList.value = await Promise.all(  
      imgList.value.map(async (item:any) => {  
        const result = await service.get<any, any>(`/file/oss/view/${item.buckName}/${item.fileName}`);  
        return 'data:image/png;base64,'+result.data
      })  
    );  
  total.value = result.total
    }
  isLoading.value = false
}
const user = ref()
onMounted(() => {
  
  user.value = JSON.parse(sessionStorage.getItem('userInfo') as any) 
  console.log(user.value)
  getListParms.value.prodUserName =  user.value?.userName || '';
  getTableList()
})

const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令号',
    inputValue: ''
  },
  {
    type: 'select',
    selectP: '品牌',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入货号',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '客户交期',
    dateValue: ''
  },
  {
    type: 'select',
    selectP: '采集员',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'date',
    dateLabel: '完成日期',
    dateValue: ''
  },
  {
    type: 'radio1',
    checkboxLabel: '全部',
    checked: false,
    label: '0'
  },
  {
    type: 'radio1',
    checkboxLabel: '正单',
    checked: false,
    label: '1'
  },
  {
    type: 'radio1',
    checkboxLabel: '补单',
    checked: false,
    label: '2'
  },
  {
    type: 'button',
    checkboxLabel: '查询'
  },
  {
    type: 'button',
    checkboxLabel: '置空'
  },
  {
    type: 'button',
    checkboxLabel: '删除扫描记录'
  },
  {
    type: 'button',
    checkboxLabel: '查询所有采集信息'
  }
])
const tableData = ref([])
const isLoading = ref(true)
const scanCode = ref('')
const scanMes = ref('')
const imgList = ref<any>([])
const flagBC = ref('0')
const scanMessage = ref('')
const radio = ref('正单')
// 查询员工信息
const getStaffListParms = ref('')
const  getStaffLis = ref({
  workerId:'',
  workerName:''
})
const getStaffListMethods = async () => {
  const result = await getStaffList(getStaffListParms.value)
    getStaffLis.value.workerId = result.workerId
    getStaffLis.value.workerName = result.workerName
    scanMessage.value = result.workerName
  console.log(result) 
}
watch(
  scanCode,
  debounce(async (val) => {
    if (!scanCode.value) return
    if (scanCode.value.includes('-')) {
      let res = {} as any
      if (radio.value === '正单') {
        res = (await service.post(`/mes/pc/order/prodStatus/doStitchCollect`, {
          orderId: scanCode.value.toUpperCase(),
      dutyDept: Launchform1Parms.value.vendor,
      dutyReason: Launchform1Parms.value.dutyReason,
      prodQty: Launchform1Parms.value.prodQty,
      prodType: radio.value === '正单' ? '正单' : '补单',
      stitchBarcode: "",
      workId: getStaffLis.value.workerId,
      workName:getStaffLis.value.workerName
        })) as any
      } else if (radio.value === '补单') {
        if (!formList2.value[0].selectValue) {
          JMessage.error('请选择责任部门(厂商)')
          return
        }
        if (!formList2.value[1].inputValue) {
          JMessage.error('请输入补单原因')
          return
        }
        if (!formList2.value[2].inputValue) {
          JMessage.error('请输入补单数量')
          return
        }
        res = (await service.post(`/mes/pc/order/prodStatus/doStitchCollect`, {
          orderId: scanCode.value.toUpperCase(),
          dutyDept: Launchform1Parms.value.vendor,
          dutyReason: Launchform1Parms.value.dutyReason,
          prodQty: Launchform1Parms.value.prodQty,
          prodType: radio.value === '正单' ? '正单' : '补单',
          stitchBarcode: "",
          workId: getStaffLis.value.workerId,
          workName:getStaffLis.value.workerName
            })) as any
      }

      if (res.code === 200) {
        JMessage.success('扫描成功')
        scanMes.value = scanCode.value
        scanCode.value = ''
        getTableList()
      } else {
        JMessage.error(res.msg)
      }
    } else {
      let res = await service.get<any, any>(`/mes/pcStitchWorker/getStitchById?workerId=${scanCode.value}`)

        user.value.id = res.workerId
        user.value.name = res.workerName
        scanMes.value = res.workerName
        getStaffLis.value.workerId = res.workerId
        getStaffLis.value.workerName = res.workerName
        scanMessage.value = res.workerName
        ElMessage.success('获取员工成功')
        scanCode.value = ''
    }
  }, 500)
)

const handleCloseMateriaLKlc14 = () => {
  ElMessageBox.confirm('确认要删除吗?')
    .then(async () => {
      handleDeleteList()
    })
    .catch(() => {})
}
const findClicked = async (content: string) => {
  if (content === '删除扫描记录') {
    if (deleteListParms.value === undefined) {
      ElMessage.warning('请选择要删除的扫描记录')
      return 
    } 
    handleCloseMateriaLKlc14()
  }
  if (content === '查询所有采集信息') {
    getListParms.value.prodUserName = ''
    getTableList()
  }
  if(content === '查询'){
     getListParms.value.prodUserName = user.value?.userName || '';
     getTableList() 
  }
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
}
const Launchform1Parms = ref({
  vendor:'',
  dutyReason:'',
  prodQty:''
})
const Launchform1 = (row:any) => {
  Launchform1Parms.value.vendor = row[0].selectValue
  Launchform1Parms.value.dutyReason = row[1].inputValue
  Launchform1Parms.value.prodQty = row[2].inputValue
}

const handleKeyDown = async (e: any) => {
  // console.log('1111')
  // if (e.key === 'Enter' || e.keyCode === 13) {
  //   await getStaffListMethods()
  //   const res = (await service.post(`/mes/pc/order/prodStatus/doStitchCollect`, {
  //     orderId: scanCode.value.toUpperCase(),
  //     cutMtl: radio.value === '正单' ? '正单' : '补单',
  //     dutyDept: Launchform1Parms.value.vendor,
  //     dutyReason: Launchform1Parms.value.dutyReason,
  //     prodQty: Launchform1Parms.value.prodQty,
  //     prodType: "正单",
  //     stitchBarcode: "",
  //     workId: getStaffLis.value.workerId,
  //     workName:getStaffLis.value.workerName
  //   })) as any
  //   if (res.code === 200) {
  //     JMessage.success('扫描成功')
  //     getTableList()
  //     const tempCode = JSON.parse(JSON.stringify(scanCode.value))
  //     scanCode.value = ''
  //     flagBC.value = '1'
  //     scanMessage.value = tempCode
  //   } else {
  //     JMessage.error(res.message)
  //     flagBC.value = '2'
  //     scanMessage.value = res.message
  //   }
  // }
}

const tableHeader = ref([
  {
    label: '采集类型',
    prop: 'prodType',
    change:true
  },
  {
    width: 170,
    label: '指令号',
    prop: 'orderId',
    change:true
  },
  {
    label: '品牌',
    prop: 'brand',
    change:true
  },
  {
    label: '货号',
    prop: 'style',
    change:true
  },
  {
    label: '颜色',
    prop: 'color',
    change:true
  },
  {
    label: '号码',
    prop: 'sizeNo',
    width: 50,
    change:true
  },
  {
    label: '订单数量',
    prop: 'orderQty',
    change:true
  },
  {
    label: '客户交期',
    prop: 'deliveryDate',
    change:true
  },
  {
    label: '生产员工',
    prop: 'workerName',
    change:true
  },
  {
    label: '派工数量',
    prop: 'prodQty',
  },
  {
    label: '采集员',
    prop: 'prodUserName',
    change:true
  },
  {
    label: '责任单位',
    prop: 'dutyDept',
    change:true
  },
  {
    label: '补单原因',
    prop: 'dutyReason',
    change:true
  },
  {
    label: '扫描时间',
    prop: 'prodDate',
    change:true
  },
  {
    type: 'img',
    label: '图片',
    prop: 'photoPath',
    srcList: imgList
  }
])
const total = ref(0)
// 定义每页显示数量改变事件
const handleSizeChange = (val: number) => {

}
// 定义当前页改变事件
const handleCurrentChange = (val: number) => {
}
</script>
<style lang="less" scoped>
.susses {
  background-color: rgb(71, 232, 71);
  text-align: center;
  line-height: 25px;
  font-size: 20px;
}
.error {
  background-color: #ff0000;
  font-size: 20px;
  text-align: center;
}
@media print {
  html,
  body {
    margin: 0;
    padding: 0;
    width: 60mm;
    height: 40mm;
  }
}
p {
  margin: 0;
}
.List {
  font-size: 10px;
  display: flex;
  justify-content: space-evenly;
}

.left {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
}

.right {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: start;
}

img {
  width: 80px;
  height: 80px;
}
</style>
